package cn.com.gridinfo.sooc.utils.versionHttp;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.CookieSpec;
import org.apache.http.cookie.CookieSpecFactory;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BrowserCompatSpec;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Post extends HttpPost {
    String httpUrl;
    //数据异常
    public static String DATAERROR = "DATAERROR";
    //服务器异常
    public static String SERVICEERROR = "SERVICEERROR";

    protected List<NameValuePair> params = new ArrayList<NameValuePair>();

    public Post(String httpUrl) {// 构造函数
        super(httpUrl);
        this.httpUrl = httpUrl;

    }

    public void addParam(String name, Object value) {// 添加参数
        BasicNameValuePair param = new BasicNameValuePair(name,
                value.toString());
        params.add(param);
    }

    /**
     * 进行Post请求，返回数据
     *
     * @return
     */
    public String getResultString() {
        String strResult = null;
        try {
            HttpEntity httpentity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
            // 请求httpRequest
            this.setEntity(httpentity);
            // 取得默认的HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            // 取得HttpResponse
            CookieSpecFactory csf = new CookieSpecFactory() {
                public CookieSpec newInstance(HttpParams params) {
                    return new BrowserCompatSpec() {
                        @Override
                        public void validate(Cookie cookie, CookieOrigin origin)
                                throws MalformedCookieException {
                            // Oh, I am easy
                        }
                    };
                }
            };
            // 允许cookie

            ((AbstractHttpClient) httpclient).getCookieSpecs().register("easy",
                    csf);
            httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
                    "easy");
//			httpclient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, false);
            HttpResponse httpResponse = httpclient.execute(this);
            // HttpStatus.SC_OK表示连接成功
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                strResult = EntityUtils.toString(httpResponse.getEntity(),
                        HTTP.UTF_8);
            } else {
                // 连接失败
                return DATAERROR;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return SERVICEERROR;
        }
        return strResult;
    }

    public String postFiles() {
        String strResult = new String();
        try {
            MultipartEntity entity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);
            for (int index = 0; index < params.size(); index++) {
                if (params.get(index).getName().equalsIgnoreCase("pic")
                        || params.get(index).getName().equalsIgnoreCase("file")
                        || params.get(index).getName().equalsIgnoreCase("img")
                        || params.get(index).getName().equalsIgnoreCase("uhead")) {
                    File file = new File(params.get(index).getValue());
                    String fileType = file.getName();
                    fileType = fileType.substring(fileType.lastIndexOf('.') + 1);
                    entity.addPart(params.get(index).getName(), new FileBody(
                            file, file.getName(), fileType, HTTP.UTF_8));
                } else {
                    entity.addPart(params.get(index).getName(),
                            new StringBody(params.get(index).getValue(),
                                    Charset.defaultCharset()));
                }
            }

            // 请求httpRequest
            this.setEntity(entity);
            // 取得默认的HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            // 取得HttpResponse
            HttpResponse httpResponse = httpclient.execute(this);
            if (httpResponse.getEntity() != null) {
            }
            // HttpStatus.SC_OK表示连接成功
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 取得返回的字符串
                strResult = EntityUtils.toString(httpResponse.getEntity(),
                        HTTP.UTF_8);
                // 连接成功，跳转到应用主界面
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("code", 404);
                map.put("message", "资源未找到");
                strResult = map.toString();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return strResult;
    }

    public static String executeGet(String url) throws Exception {
        BufferedReader in = null;

        String content = null;
        try {
            // 定义HttpClient
            HttpClient client = new DefaultHttpClient();
            // 实例化HTTP方法
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);

            in = new BufferedReader(new InputStreamReader(response.getEntity()
                    .getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            content = sb.toString();
        } finally {
            if (in != null) {
                try {
                    in.close();// 最后要关闭BufferedReader
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        return content;
    }
}